<template>
  <div class="mayTable">
    <el-table
      border
      :show-header="false"
      :data="tableData"
      style="width: 100%"
      @cell-click="cellClickHandler"
    >
      <el-table-column v-for="key in columnData" :key="key" :prop="key">
        <template slot-scope="scope">
          <div :class="scope.row[key].isSelected ? 'selected' : ''">
            {{ scope.row[key].value }}
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      tableSelectData: []
    };
  },
  computed: {
    columnData() {
      if (this.data.length) {
        const item = this.data[0];
        return Object.keys(item);
      }
      return [];
    },
    tableData() {
      return this.data.map((row, rowIndex) => {
        const result = {};
        const rowSelectData = this.tableSelectData[rowIndex] || {};
        Object.keys(row).forEach(key => {
          result[key] = {
            value: row[key],
            isSelected: rowSelectData[key]
          };
        });
        return result;
      });
    }
  },
  methods: {
    cellClickHandler(row, column) {
      const rowIndex = this.tableData.indexOf(row);
      const columnKey = column.property;
      this.toggleSelectData(rowIndex, columnKey);
    },
    toggleSelectData(row, column) {
      let columnData = this.tableSelectData[row];
      if (columnData === undefined) {
        columnData = {};
      }
      let value = columnData[column];
      columnData[column] = !value;
      this.$set(this.tableSelectData, row, columnData);
      this.$emit("input", this.tableSelectData);
    }
  },
  watch: {
    data() {
      this.tableSelectData = [];
      this.$emit("input", this.tableSelectData);
    }
  }
};
</script>

<style lang="scss">
.mayTable {
  .el-table {
    td {
      padding: 0;
      .cell {
        padding: 0;
        div {
          padding: 12px 10px;
          &.selected {
            background:#f9f7ad
          }
        }
      }
    }
    &.el-table--border td:first-child .cell {
      padding: 0;
    }
  }
}
</style>
